package service

import (
	"context"
	"errors"
	"mall_2.0/config"
	"mall_2.0/consts"
	"mall_2.0/pkg/utils/ctl"
	"mall_2.0/pkg/utils/log"
	"mall_2.0/respository/db/dao"
	"mall_2.0/respository/db/model"
	"mall_2.0/types"
	"sync"
)

var FavoriteSrvIns *FavoriteSrv
var FavoriteSrvOnce sync.Once

type FavoriteSrv struct{}

func GetFavoriteSrv() *FavoriteSrv {
	FavoriteSrvOnce.Do(func() {
		FavoriteSrvIns = &FavoriteSrv{}
	})
	return FavoriteSrvIns
}

// FavoriteCreate 收藏商品
func (s *FavoriteSrv) FavoriteCreate(ctx context.Context, req *types.FavoriteCreateReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	favoriteDao := dao.NewFavoriteDao(ctx)
	exist, _ := favoriteDao.FavoriteExistOrNot(req.ProductId, u.ID)
	if exist {
		err = errors.New("该商品已收藏")
		log.LogrusObj.Error(err)
		return
	}
	userDao := dao.NewUserDao(ctx)
	user, err := userDao.GetUserById(u.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	bossDao := dao.NewUserDaoByDB(userDao.DB)
	boss, err := bossDao.GetUserById(user.ID)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	productDao := dao.NewProductDao(ctx)
	product, err := productDao.GetProductByID(req.ProductId)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	favorite := &model.Favorite{
		UserID:     user.ID,
		User:       *user,
		ProductID:  product.ID,
		Product:    *product,
		BossUserID: boss.ID,
		Boss:       *boss,
	}
	err = favoriteDao.CreateFavorite(favorite)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// FavoriteDelete 取消收藏
func (s *FavoriteSrv) FavoriteDelete(ctx context.Context, req *types.FavoriteDeleteReq) (resp interface{}, err error) {
	err = dao.NewFavoriteDao(ctx).DeleteFavorite(req.Id)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// FavoriteList 获取收藏列表
func (s *FavoriteSrv) FavoriteList(ctx context.Context, req *types.FavoritesServiceReq) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(ctx)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	favorites, total, err := dao.NewFavoriteDao(ctx).ListFavoriteByUID(u.ID, &req.BasePage)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	for i := range favorites {
		if config.Config.System.UploadModel == consts.UploadModelLocal {
			favorites[i].ImgPath = config.Config.PhotoPath.PhotoHost + config.Config.System.HttpPort + config.Config.PhotoPath.ProductPath + favorites[i].ImgPath
		}
	}
	resp = &types.DataListResp{
		Item:  favorites,
		Total: total,
	}
	return
}
